package ar.edu.uba.fi.jmit.graphvisualizer.server.service;

import java.io.Serializable;
import java.text.DateFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import ar.edu.uba.fi.jmit.graphvisualizer.client.AlertService;
import ar.edu.uba.fi.jmit.graphvisualizer.server.ResourceProperties;
import ar.edu.uba.fi.jmit.graphvisualizer.server.storage.Pair;
import ar.edu.uba.fi.jmit.graphvisualizer.server.storage.Registry;
import ar.edu.uba.fi.jmit.graphvisualizer.shared.AlertInfo;

public class AlertServiceImpl extends AbstractServiceImpl implements AlertService {
	
	private static final long serialVersionUID = 8340489492216220918L;
	private static final DateFormat dateFormat = java.text.SimpleDateFormat.getInstance();

	@Override
	public List<AlertInfo> getLastReceivedAlerts() {
		return this.generateAlertInfoList(Registry.getAlertDataStorage().getData());
	}

	private List<AlertInfo> generateAlertInfoList(
			List<Pair<Map<String, Serializable>>> data) {
		List<Pair<Map<String, Serializable>>> pairList = Registry.getAlertDataStorage().getData();
		List<AlertInfo> alertInfoList = new LinkedList<AlertInfo>();
		for(Pair<Map<String, Serializable>> pair:pairList) {
			alertInfoList.add(this.createAlertInfo(pair));
		}
		return alertInfoList;
	}

	private AlertInfo createAlertInfo(Pair<Map<String, Serializable>> pair) {
		AlertInfo alertInfo = new AlertInfo();
		alertInfo.setAlertTime(dateFormat.format(pair.getDate()));
		alertInfo.setApplication(getApplication(pair.getValue()));
		alertInfo.setMonitor(getMonitor(pair.getValue()));
		alertInfo.setSeverity(getSeverity(pair.getValue()));
		alertInfo.setMessage(getMessage(pair.getValue()));
		return alertInfo;
	}

	private String getMessage(Map<String, Serializable> value) {
		return value.get(ResourceProperties.getProperty("jmit.graphvisualizer.range.description")).toString();
	}

	private String getSeverity(Map<String, Serializable> value) {
		return value.get(ResourceProperties.getProperty("jmit.graphvisualizer.range.severity")).toString();
	}

	private String getMonitor(Map<String, Serializable> value) {
		return value.get(ResourceProperties.getProperty("jmit.graphvisualizer.key.monitorName")).toString();
	}

	private String getApplication(Map<String, Serializable> value) {
		return value.get(ResourceProperties.getProperty("jmit.graphvisualizer.monitor.clientApplicationName")).toString();
	}

}
